package com.zlx.store.order.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zlx.store.domain.entity.vo.AlipayVO;
import com.zlx.store.domain.entity.vo.OrderVO;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

// xjlugv6874@sandbox.com
// 9428521.24 - 30 = 9428491.24 + 30 = 9428521.24
@RestController
@RequestMapping("/alipay")
public class AliPayController {

    private static final String GATEWAY_URL =
            "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @RabbitListener(queues = "orderPayQueue")
    @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(AlipayVO aliPay, HttpServletResponse httpResponse, OrderVO orderVO) throws Exception {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi-sandbox.dl.alipaydev.com/gateway.do", "9021000123612031",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7dQ9ShJH6lysWBnUEesGVkIHBbbjuhRbXS0DVLRHuEpczkL3q9UuAOI6Y/xzU2+gaKzkM5PQfI8U0neA+QkixkSbb5NiXrzji5zcebFZxaonH5pcQnTF4PX8NSt93aiVI2SObM2hHMnp2+JA6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6Iwk2FqtukxfRw0jSOtU6pPj0SRDNYQYbVliSYXezbIHj4PpxyRl03jFJpCkM/CZCd3PxAWMDcj3R7d/fTjks3FRkBuo2ZBeSPDtRPIvrJB8cLSuRKR/bFRQ6Fy70E+5iHRAZzEOSqBMRMrIHBAoGAYjpcLgDO7L3Mo3uWFIDiyy/JbzcjPikwoGkR1w4O1iR8t4Vu0jNrYw9xB+q4hE1yI9Hmg6CXb8ssCvhvRF42KD7qg/SH1/Ip/+Wij0gOasMdVYL5A49fqiNukhQw+kv/wX9exPMUtkzi3/iXKtW3Tz9X0NzEJ9lD5KS3rfrpRXU="
                , "JSON", "UTF-8",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzWLsTCbWb2wdDsmJLmm6hl4Um4FLUZuPXqJbLF6ifWpXVG42okLDgg/6y4vYJabuxf9+a+C3QEhvZLCwhG3rzMWX/cMaNRQcrgZ10sgszTM+eo9mKLSDwohbZrYIecmP5kiCcwfpCUdzANXw/Lu0kBtuVgsKILi3gzSP6fATQ2Brj387vqLBqG1ZLMSthvUIMwpozQf9S2pdPqKetfU0Pu0sxK5s30v7Zb0ICDPSkbsAxBdtcdqdcIAeoz5MC48XcYq+AKD3dJMVhtaezfWKWoqG3cIroB5/dxM9iQanyJT6QEkMirK0uohFETYP46c3r2rIwrvSbqeIx1XnLGOG+wIDAQAB",
                "RSA2");
        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl("http://muaqx9.natappfree.cc/alipay/notify");
        JSONObject bizContent = new JSONObject();
        aliPay.setTotalAmount(orderVO.getOrderAmount());
        aliPay.setGoodsVoList(orderVO.getGoodsVOList());
        aliPay.setTraceNo(Long.toString(orderVO.getOrderId()));
        bizContent.set("out_trade_no", aliPay.getTraceNo());  // 我们自己生成的订单编号
        bizContent.set("total_amount", aliPay.getTotalAmount()); // 订单的总金额
        bizContent.set("subject", aliPay.getGoodsVoList());   // 支付的物品列表
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());
        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        //创建payOrder更改redis中的payOrder状态为待支付
        rabbitTemplate.convertAndSend("order_check_exchange","order_check_queue"
               , orderVO,mmp->{
                mmp.getMessageProperties().setExpiration(String.valueOf(1000*30*60));
                return mmp;});
    }

    @RabbitListener(queues = "mq_dlx_queue")
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request, OrderVO orderVO) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

//            String outTradeNo = params.get("out_trade_no");
//            String gmtPayment = params.get("gmt_payment");
//            String alipayTradeNo = params.get("trade_no");

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign,
                    "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7dQ9ShJH6lysWBnUEesGVkIHBbbjuhRbXS0DVLRHuEpczkL3q9UuAOI6Y/xzU2+gaKzkM5PQfI8U0neA+QkixkSbb5NiXrzji5zcebFZxaonH5pcQnTF4PX8NSt93aiVI2SObM2hHMnp2+JA6texqJHqLfg/vZ+7BYwTpNKnANUR0w2pgjDupQqZjVyR8UtgWqD+qrcoLko4rd4dzu85Z9AK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WMDcj3R7d/fTjks3FRkBuo2ZBeSPDtRPIvrJB8cLSuRKR/bFRQ6Fy70E+5iHRAZzEOSqBMRMrIHBAoGAYjpcLgDO7L3Mo3uWFIDiyy/JbzcjPikwoGkR1w4O1iR8t4Vu0jNrYw9xB+q4hE1yI9Hmg6CXb8ssCvhvRF42KD7qg/SH1/Ip/+Wij0gOasMdVYL5A49fqiNukhQw+kv/wX9exPMUtkzi3/iXKtW3Tz9X0NzEJ9lD5KS3rfrpRXU="
                    , "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 查询订单
//                QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("order_id", outTradeNo);
//

//                if (orders != null) {
//                    orders.setAlipayNo(alipayTradeNo);
//                    orders.setPayTime(new Date());
//                    orders.setState("已支付");
//                    ordersMapper.updateById(orders);
//                }
            }
        }
        return "success";
    }
}